<template>
  <div>
    <table class="table table-sm table-bordered approve-table">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr class="bg-light">
          <td colspan="4" class="text-center py-2">{{ label }}</td>
        </tr>
        <template v-if="isView">
          <tr>
            <td>审批金额</td>
            <td>{{ relatedForm.res_funds }}万元</td>
            <td>审批期限</td>
            <td>{{ relatedForm.res_months }}月</td>
          </tr>
          <tr>
            <td>资金实际用途</td>
            <td colspan="3">{{ relatedForm.funds_use_dir }}</td>
          </tr>
          <tr>
            <td>拟定贷款银行</td>
            <td>{{ relatedForm.bank_name }}</td>
            <td>贷款利率（年）</td>
            <td>{{ relatedForm.load_rate || '-' }}%</td>
          </tr>
          <tr>
            <td>担保费收取方式</td>
            <td>
              {{ enumGuaFundsType[relatedForm.gua_fee_coll_type] || '' }}
            </td>
            <td>担保费率</td>
            <td>{{ relatedForm.gua_rate }}%</td>
          </tr>
          <tr>
            <td>从业人数</td>
            <td>{{ relatedData.emp_temp_total || '-' }} 人</td>
            <td>担保费</td>
            <td>{{ solidData.gua_fee || '-' }}元</td>
          </tr>
          <tr>
            <td>销售收入</td>
            <td>{{ relatedData.sale_income || '-' }} 万元</td>
            <td>资产总额</td>
            <td>{{ relatedData.assets_funds || '-' }} 万元</td>
          </tr>
          <tr>
            <td>
              带动农户
              <small class="text-muted">(建档立卡户)</small>
            </td>
            <td>{{ relatedData.poverty_households || '-' }} 人</td>
            <td>带动农户增收</td>
            <td>{{ relatedData.poverty_income || '-' }} 万元</td>
          </tr>
          <tr>
            <td>项目基本介绍</td>
            <td colspan="3" class="text-left text-indent">
              <div v-html="formatLine(relatedForm.project_des)"></div>
            </td>
          </tr>
          <tr>
            <td>反担保措施</td>
            <td colspan="3" class="text-left">
              <div v-html="formatLine(relatedForm.gua_method_des)"></div>
            </td>
          </tr>
          <tr>
            <td>
              <span v-if="!isView" class="text-danger">*</span>
              调查资料
            </td>
            <td colspan="3" class="text-left">
              <attach-main
                :related-id="relatedId"
                @status="handleAttachSuccess"
                :view-mode="isView"
              ></attach-main>
            </td>
          </tr>
          <tr>
            <td>风险审查附件</td>
            <td colspan="3" class="text-left">
              <attach-risk-main :related-id="relatedId" :view-mode="isView"></attach-risk-main>
            </td>
          </tr>

          <tr v-if="!isProSelf">
            <td>评审会纪要</td>
            <td colspan="3">
              <div v-for="file in areadyFiles" :key="file.url" class="d-flex">
                <attach-item :attach-data="file"></attach-item>
              </div>
            </td>
          </tr>
        </template>

        <template v-else>
          <tr>
            <td>
              <span class="text-danger">*</span>
              审批金额
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 4 }"
                placeholder="审批金额"
                v-model="relatedForm.res_funds"
                @change="submitKey('res_funds')"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>
              <span class="text-danger">*</span>
              审批期限
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 0 }"
                placeholder="审批期限"
                v-model="relatedForm.res_months"
                @change="submitKey('res_months')"
              >
                <span slot="append">月</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger">*</span>
              资金实际用途
            </td>
            <td colspan="3" class="report-input-td">
              <textarea
                rows="3"
                class="form-control"
                v-model="relatedForm.funds_use_dir"
                @change="submitKey('funds_use_dir')"
              ></textarea>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger"></span>
              拟定贷款银行
            </td>
            <td>
              {{ relatedForm.bank_name }}
              <!-- <el-input placeholder="拟定贷款银行" v-model="relatedForm.bank_name"></el-input> -->
            </td>
            <td>贷款利率（年）</td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, max: 100, fixed: 4 }"
                placeholder="贷款利率"
                v-model="relatedForm.load_rate"
                @change="submitKey('load_rate')"
              >
                <span slot="append">%</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>
              <span v-if="!isView" class="text-danger">*</span>
              担保费收取方式
            </td>
            <td class="report-input-td text-left">
              <div style="padding: 0.6rem; background-color: #ffffee">
                <c-radio-group
                  v-model="relatedForm.gua_fee_coll_type"
                  :options="enumGuaFundsType"
                ></c-radio-group>
              </div>
            </td>
            <td>
              <span class="text-danger">*</span>
              担保费率
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, max: 100, fixed: 4 }"
                placeholder="担保费率"
                v-model="relatedForm.gua_rate"
                @change="submitKey('gua_rate')"
              >
                <span slot="append">%</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger" v-if="isCompany">*</span>
              从业人数
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 0 }"
                placeholder="从业人数"
                v-model="relatedEdit.emp_temp_total"
                @change="submitKeyRelated('emp_temp_total')"
              >
                <span slot="append">人</span>
              </el-input>
            </td>
            <td>
              <span class="text-danger">*</span>
              担保费
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 2 }"
                placeholder="担保费"
                v-model="relatedForm.gua_fee"
                @change="submitKey('gua_fee')"
              >
                <span slot="append">元</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger" v-if="isCompany">*</span>
              销售收入
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 2 }"
                placeholder="销售收入"
                v-model="relatedEdit.sale_income"
                @change="submitKeyRelated('sale_income')"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>
              <span class="text-danger" v-if="isCompany">*</span>
              资产总额
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 2 }"
                placeholder="资产总额"
                v-model="relatedEdit.assets_funds"
                @change="submitKeyRelated('assets_funds')"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger" v-if="isCompany">*</span>
              带动农户
              <small class="text-muted">(建档立卡户)</small>
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 0 }"
                placeholder="带动农户（建档立卡户）,可填0"
                v-model="relatedEdit.poverty_households"
                @change="submitKeyRelated('poverty_households')"
              >
                <span slot="append">人</span>
              </el-input>
            </td>
            <td>
              <span class="text-danger" v-if="isCompany">*</span>
              带动农户增收
            </td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 0 }"
                placeholder="带动农户增收，可填0"
                v-model="relatedEdit.poverty_income"
                @change="submitKeyRelated('poverty_income')"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
          </tr>

          <tr>
            <td>
              <span class="text-danger">*</span>
              项目基本介绍
            </td>
            <td colspan="3" class="report-input-td">
              <textarea
                rows="3"
                class="form-control"
                @change="submitKey('project_des')"
                v-model="relatedForm.project_des"
              ></textarea>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger">*</span>
              反担保措施
            </td>
            <td colspan="3" class="report-input-td">
              <textarea
                rows="3"
                class="form-control"
                v-model="relatedForm.gua_method_des"
                @change="submitKey('gua_method_des')"
              ></textarea>
            </td>
          </tr>
          <tr>
            <td>调查资料</td>
            <td colspan="3" class="text-left">
              <attach-main
                :related-id="relatedId"
                @status="handleAttachSuccess"
                :view-mode="isView"
              ></attach-main>
            </td>
          </tr>
          <tr>
            <td>风险审查附件</td>
            <td colspan="3" class="text-left">
              <attach-risk-main :related-id="relatedId" :view-mode="isView"></attach-risk-main>
            </td>
          </tr>

          <tr v-if="!isProSelf">
            <td>
              <span class="text-danger">*</span>
              评审会纪要
            </td>
            <td colspan="3" class="report-input-td text-left">
              <div class="d-flex align-items-stretch p-2">
                <div class="mr-3">
                  <input
                    type="file"
                    ref="uploadInput"
                    class="d-none"
                    multiple
                    accept="*"
                    @change="handleFileChange"
                  />
                  <el-button
                    plain
                    size="small"
                    class="mb-1"
                    icon="el-icon-upload2"
                    style="height: 100%"
                    :disabled="saveLoading"
                    @click="handleSelectFile"
                  >
                    上传
                  </el-button>
                </div>
                <div class="flex-1 bg-light p-2 rounded">
                  <div v-for="(file, i) in areadyFiles" :key="file.url" class="d-flex">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
                      删除
                    </el-button>
                  </div>
                  <div v-for="(file, index) in uploadFiles" :key="index" class="d-flex">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button
                      type="text"
                      :disabled="saveLoading"
                      @click="handleDeleteFile(2, index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <!-- <el-button @click="submit">submit</el-button> -->
    <approve-common
      v-bind="$attrs"
      :view-mode="viewMode"
      :related-data="relatedData"
      :approve-data="approveData"
      :before-save="submit"
      @success="handleSuccess"
    ></approve-common>
  </div>
</template>

<script>
import { mul } from '@vimi/utils-tool'
import { enumGuaFundsType } from '@/credit/views/county/unionProvince/components/projectApprove/index'

import ApproveCommon from '@/credit/views/county/unionProvince/components/projectApprove/ApproveCommon'
import AttachMain from '@/credit/views/city/bus/normal/invest/AttachMain'
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { arrayFromString, arrayToString } from '@vimi/utils-tool'
import { uploadOss, deleteOss } from '@/common/api/oss'
import AttachItem from '@/bank/components/attach/Item'
import { formatLine } from '@/common/plugins/tools/format'
import AttachRiskMain from '@/credit/views/county/unionProvince/components/projectApprove/components/risk/AttachMain'
import { mapGetters } from 'vuex'
export default {
  components: {
    ApproveCommon,
    AttachItem,
    // DueReport,
    AttachMain,
    AttachRiskMain,
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    approveData: {
      type: Object,
      default: () => ({
        editable: false,
        record: [],
      }),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formatLine,
      enumGuaFundsType,
      loading: false,
      tableName: 'project_approval_register',
      relatedForm: {
        res_funds: '',
        res_months: '',
        funds_use_dir: '',
        bank_name: '',
        load_rate: '',
        gua_rate: '',
        gua_fee: '',
        project_des: '',
        gua_method_des: '',
        attachment: '',
        gua_fee_coll_type: '1',
      },

      relatedEdit: {
        emp_temp_total: '',
        sale_income: '',
        assets_funds: '',
        poverty_households: '',
        poverty_income: '',
      },
      attachFinished: false,
      uploadFiles: [],
      saveLoading: false,
      areadyFiles: [],
      solidData: {},
      deleteFiles: [],
    }
  },
  computed: {
    ...mapGetters(['org']),
    dataId() {
      return this.solidData.id
    },
    registerType() {
      return this.approveData.data?.type ?? 1
    },
    label() {
      return this.registerType === 2 ? '省农担评审登记' : '评审登记'
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
    isCompany() {
      return +this.relatedData.customer_type === 1
    },
    isSYSTEM() {
      // 系统后台状态为编辑
      return this.org.orgClass === 'org_credit_sys'
    },
    isView() {
      // return false
      if (this.isSYSTEM) {
        return false
      }
      return this.viewMode || !this.approveData.editable
    },
    guaType() {
      return +this.relatedData.gua_type
    },
    isProSelf() {
      return +this.relatedData.is_pro_dir === 1
    },

    // 自动计算担保费
    guaFee() {
      let {
        gua_fee_coll_type: type = '',
        gua_rate: rate = '',
        res_months: months = '',
        res_funds: funds = '',
      } = this.relatedForm
      type = +type
      rate = +rate * 1e-2
      funds = +funds * 1e4
      const year = Math.ceil(months / 12)
      if (type === 0 || rate === 0 || year === 0 || funds === 0) {
        return ''
      }
      if (type === 1) {
        return mul(funds, rate, year)
      }
      if (type === 2) {
        return mul(funds, rate)
      }
      return ''
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        Object.keys(this.relatedEdit).forEach(key => {
          this.relatedEdit[key] = this.relatedData[key] || ''
        })
        this.getData()
      },
      immediate: true,
      deep: true,
    },
    guaFee(val) {
      this.relatedForm.gua_fee = val
    },
  },
  created() {},
  mounted() {},
  methods: {
    submitKeyRelated(key) {
      const data = {}
      data[key] = this.relatedEdit[key] || null
      this.$api.updateData(this.$serviceName, 'customer_related', this.relatedId, data)
    },
    async submitKey(key) {
      const data = {}
      data[key] = this.relatedForm[key]
      if (['load_rate', 'gua_rate'].includes(key) && +(this.relatedForm.load_rate || '') > 100) {
        return
      }
      if (key === 'gua_rate') {
        data.gua_fee = this.relatedForm.gua_fee
      }
      if (this.dataId) {
        await this.updateData(this.dataId, data)
      } else {
        const editForm = {}
        Object.keys(this.relatedForm).forEach(key => {
          editForm[key] = this.relatedForm[key] || null
        })
        // 添加把所有初始化值添加，修改只针对key
        await this.addData({
          ...editForm,
          customer_related_id: this.relatedId,
        })
      }
      this.getData()
    },
    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },
    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },
    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },
    handleAttachSuccess(status) {
      this.attachFinished = +status === 1
    },
    setUserLabel(select) {
      this.relatedForm.use_category_name = select.value || ''
    },
    getData() {
      if (!this.relatedId) return

      this.loading = true
      this.$api
        .getData({
          table: this.tableName,
          params: {
            'customer_related_id.eq': this.relatedId,
            'approval_register_type.eq': this.registerType,
          },
        })
        .then(res => {
          this.solidData = res?.data?.[0] ?? {}
          this.initForm(this.solidData)
        })
        .finally(() => {
          this.loading = false
        })
    },
    validate() {
      const validatePairs = {
        res_funds: '请填写审批金额',
        res_months: '请填写审批期限',
        bank_name: '请填写拟定贷款银行',
        // load_rate: '请填写贷款利率',
        gua_rate: '请填写担保费率',
        gua_fee: '请填写担保费',
        funds_use_dir: '请填写资金实际用途',
        project_des: '请填写项目基本介绍',
        gua_method_des: '请填写反担保措施',
      }

      for (const key in validatePairs) {
        if (!this.relatedForm[key]) {
          return validatePairs[key]
        }
      }

      const validateRelated = {
        emp_temp_total: '请输入从业人数, 不能为0',
        sale_income: '请输入销售收入, 不能为0',
        assets_funds: '请输入资产总额, 不能为0',
      }
      for (const key in validateRelated) {
        if (this.isCompany && !+this.relatedEdit[key]) {
          return validateRelated[key]
        }
      }
      const validateRelatedZero = {
        poverty_households: '请输入带动农户, 可填0',
        poverty_income: '请输入带动农户增收, 可填0',
      }
      for (const key in validateRelatedZero) {
        if (this.isCompany && !this.relatedEdit[key]) {
          if (this.relatedEdit[key] !== 0) {
            return validateRelatedZero[key]
          }
        }
      }

      if (this.areadyFiles.length + this.uploadFiles.length === 0 && !this.isProSelf) {
        return '请先上传评审会纪要'
      }

      return ''
    },

    initForm(val) {
      this.reset()

      Object.keys(this.relatedForm).forEach(key => {
        this.relatedForm[key] = val[key] || ''
      })
      this.relatedForm.bank_name = this.relatedData.bank_name

      if (!val.id) {
        const keyMap = {
          funds_use_dir: 'funds_use_dir',
          gua_method_des: 'counter_guarantee',
          res_funds: 'approved_funds',
          res_months: 'months',
          project_des: 'project_des',
          bank_name: '',
          load_rate: '',
          gua_rate: '',
          gua_fee: '',
        }
        Object.keys(keyMap).forEach(key => {
          this.relatedForm[key] = this.relatedData[keyMap[key] || key] || ''
        })
        this.relatedForm.gua_fee_coll_type = this.relatedForm.gua_fee_coll_type || '1'
      }

      this.areadyFiles = arrayFromString(val.attachment).reduce((prev, curr) => {
        prev.push(
          attachAdapter({
            attachment: curr,
          })
        )
        return prev
      }, [])
    },
    reset() {
      this.uploadFiles.forEach(file => {
        revokeObjectURL(file.url)
      })
      this.uploadFiles = []
      this.areadyFiles = []
      this.deleteFiles = []

      this.resetInput()
    },
    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },

    async submit() {
      const msg = this.validate()
      if (msg) {
        this.$message.error(msg)
        return false
      }

      if (!this.attachFinished) {
        this.$message.error('请先完善附件资料！！')
        return false
      }

      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/approve/register/${this.relatedId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      const numKey = [
        'emp_temp_total',
        'sale_income',
        'assets_funds',
        'poverty_households',
        'poverty_income',
      ]
      numKey.forEach(key => {
        // 后端不能传字符串空
        this.relatedEdit[key] = this.relatedEdit[key] || null
      })
      this.saveLoading = true
      await this.$api
        .updateData(this.$serviceName, 'customer_related', this.relatedId, this.relatedEdit)
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
      return Promise.all(promises)
        .then(list => {
          const attachment = arrayToString([...this.areadyFiles.map(it => it.url), ...list])

          const data = {
            ...this.relatedForm,
            customer_related_id: this.relatedId,
            attachment,
          }
          return this.dataId ? this.updateData(this.dataId, data) : this.addData(data)
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.deleteOssFiles()
          this.saveLoading = false
        })
    },
    addData(data) {
      return this.$api.addData({
        table: this.tableName,
        data,
      })
    },

    updateData(id, data) {
      return this.$api.updateData({
        table: this.tableName,
        id,
        data,
      })
    },

    handleSuccess(res) {
      this.$emit('success', res)
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
